package se.joinenea.bishopsarm;

import java.io.IOException;

import android.graphics.Color;
import android.os.Handler;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ColorGame implements Game {

    private final BishopsArm bishopsArm;
    private final NXTBot nxtBot;
    private final Button buttonStartGame;
    private final LinearLayout gameArea;
    private final TextView colorView;
    private final TextView clockView;
    private final Runnable colorSenseTask;
    private final Handler handler;


    private final int[] targetColors = {
            Color.GREEN,
            Color.BLUE,
            Color.YELLOW,
            Color.RED
    };
    boolean running;
    private int targetColorIdx;
    private final NXTColorSensorHandler nxtColorSensorHandler;
    private final StopWatch chronometer;

    public ColorGame(BishopsArm bishopsArm, NXTBot nxtBot) throws IOException {
        this.bishopsArm = bishopsArm;
        this.nxtBot = nxtBot;
        this.buttonStartGame =
                (Button) this.bishopsArm.findViewById(R.id.buttonStartGame);
        this.gameArea =
                (LinearLayout) this.bishopsArm.findViewById(R.id.GameArea);
        this.colorView =
                (TextView) this.bishopsArm.findViewById(R.id.colorView);
        this.colorView.setEnabled(false);
        this.clockView =
                (TextView) this.bishopsArm.findViewById(R.id.clockView);
        this.running = false;
        this.colorSenseTask = new ColorSenseTask();
        this.handler = new Handler();
        this.nxtColorSensorHandler = new NXTColorSensorHandler(this.nxtBot);
        nxtColorSensorHandler.initColorSensor();
        this.chronometer = new StopWatch();
    }

    public void colorSensed(int color) {
        if (isTargetColor(color)) {
            if (!isGameOver()) {
                changeTargetColor();
            } else {
                stop();
                long millis = chronometer.stop();
                showResult(millis);
            }
        }
    }

    private void showResult(long millis) {
        colorView.setBackgroundColor(Color.WHITE);
        colorView.setText(R.string.gameSuccess);
        long seconds = millis / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        millis = millis % 1000;
        clockView.setText(String.format("%02d:%02d.%03d", minutes, seconds,
                millis));
    }

    private void changeTargetColor() {
        if (++targetColorIdx < targetColors.length) {
            colorView.setBackgroundColor(targetColors[targetColorIdx]);
        }
    }

    private boolean isGameOver() {
        return targetColorIdx == targetColors.length - 1;
    }

    private boolean isTargetColor(int color) {
        return targetColorIdx < targetColors.length
                && color == targetColors[targetColorIdx];
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public void stop() {
        // TODO Auto-generated method stub
        handler.removeCallbacks(colorSenseTask);
        buttonStartGame.setText(R.string.startGame);
        running = false;
    }

    @Override
    public void start() {
        // TODO Auto-generated method stub
        // Setup a timer that pings the colorsensor, 2 consecutive readings
        // showing the same value is a successful registration
        // Start a stopwatch

        buttonStartGame.setText(R.string.stopGame);

        targetColorIdx = 0;
        colorView.setBackgroundColor(targetColors[targetColorIdx]);
        colorView.setText(R.string.gameTarget);
        colorView.setEnabled(true);
        // Start reading color values once a second
        handler.postDelayed(colorSenseTask, 1000);
        //nxtBot.schedule(colorSenseTask, 100, 1000);
        chronometer.start();
        running = true;
    }

    private final class ColorSenseTask implements Runnable {
        private int lastColor = 0;

        @Override
        public void run() {
            if (isRunning()) {
                int color = 0;
                try {
                    color = nxtColorSensorHandler.getColorVal();
                } catch (IOException e) {
                    bishopsArm.showMessage(e.getMessage());
                }
                if (color == lastColor) {
                    colorSensed(color);
                }
                lastColor = color;
            }
            handler.postDelayed(this, 1000);
        }
    }


}
